﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.Entities.Relations.InferredAssociations
{
    public class ClusteringWorker:IWorker 
    {
        #region fields
        private Thread _WorkerThread;
        private ClusteringInstruction _Instruction;
        private ClusteringOutput _Output;
        private Guid _JobTicketID;
        private RunContext _Context;
        private string _WorkflowName;
        private string _ComponentName;

        /// <summary>
        /// 
        /// </summary>
        public string ComponentName
        {
            get { return _ComponentName; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string WorkflowName
        {
            get { return _WorkflowName; }
        }
        #endregion

        #region IWorker Members

        public Thread WorkerThread
        {
            get { return _WorkerThread; }
        }

        public InstructionBase Instruction
        {
            get { return _Instruction; }
        }

        public ResultBase Output
        {
            get { return _Output; }
        }

        public Type ComponentType
        {
            get { return typeof(ClusteringComponent); }
        }

        public RunContext Context
        {
            get { return _Context; }
            set { _Context = value; }
        }

        public void SetInstruction(Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._JobTicketID = ticketGuid;
            this._Instruction = (ClusteringInstruction)request;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }

        public void SetInstruction(RunContext context, Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._JobTicketID = ticketGuid;
            this._Instruction = (ClusteringInstruction)Instruction;
            this._Context = context;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }

        public void DoWork()
        {
            if (this.WorkerStartedEvent != null)
            {
                this.WorkerStartedEvent(this._JobTicketID, this, this.GetType(), this._Instruction);
            }
            this._WorkerThread = Thread.CurrentThread;
            this.ClusterEntities();
        }

        public void DoWorkAsync()
        {
            if (this.WorkerStartedEvent != null)
            {
                this.WorkerStartedEvent(this._JobTicketID, this, this.GetType(), this._Instruction);
            }
            this._WorkerThread = new Thread(new ThreadStart(this.ClusterEntities));
            this._WorkerThread.Start();
        }

        public void CancelWork()
        {
            if (this._WorkerThread != null && this._WorkerThread.IsAlive)
            {
                this._WorkerThread.Abort();
                if (this.WorkerCancelledEvent != null)
                {
                    this.WorkerCancelledEvent(this._JobTicketID, this.GetType(), this._Instruction);
                }
            }

        }

        public event WorkerStarted WorkerStartedEvent;
        public event WorkerFinished WorkerFinishedEvent;
        public event WorkerHasError WorkerErredEvent;
        public event WorkerCancelled WorkerCancelledEvent;
        public event WorkerStatusChanged WorkerStatusChangedEvent;

        #endregion

        #region work
        private void ClusterEntities()
        {
            try
            {
                IClusterCalculator clusterCalc = null;
                string binFolderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                DirectoryInfo binDirInfo=new DirectoryInfo(binFolderPath);
                FileInfo[] dllFileInfos = binDirInfo.GetFiles("*.dll", SearchOption.TopDirectoryOnly);
                foreach(FileInfo fileInfo in dllFileInfos)
                {
                    Assembly assembly = Assembly.LoadFile(fileInfo.FullName);
                    Type[] types = assembly.GetTypes();
                    foreach(Type type in types)
                    {
                        if(type.FullName==this._Instruction.ClusterCalculatorTypeName)
                        {
                            clusterCalc = (IClusterCalculator) Activator.CreateInstance(type);
                            break;
                        }
                    }
                    if(clusterCalc !=null)
                        break;
                }

                if(clusterCalc==null)
                    throw new Exception("Unable to find cluster worker class");

                
                if(this.WorkerFinishedEvent !=null)
                {
                    this.WorkerFinishedEvent(this._JobTicketID, this.GetType(), this._Instruction, this._Output);   
                }
            }
            catch (Exception ex)
            {
                if(this.WorkerErredEvent !=null)
                {
                    this.WorkerErredEvent(this._JobTicketID, this.GetType(), this._Instruction, ex.ToString(),true);
                }
            }
        }

        

        #endregion

        #region read input
        private List<Entity> ReadInputEntities(string path)
        {
            List<Entity> entities = new List<Entity>();
            return entities;
        }
        #endregion

        #region save output
        private void SaveClusterResult(string resultFilePath, Dictionary<Cluster,Dictionary<Entity,double>> clusteredEntities)
        {
            
        }
        #endregion
    }
}
